package _04_queue.my_implements;

import _04_queue.AbstractQueue;
import _04_queue.Queue;

import java.util.Iterator;
import java.util.StringJoiner;

/**
 * @author: mornd
 * @dateTime: 2023/6/4 - 21:08
 * 单向环形带哨兵的链表2
 * 自己写的，不推荐使用，内部不创建 Node 内部类，head，tail 都是 LinkedListQueue2 类型
 */
public class LinkedListQueue2<E> extends AbstractQueue<E> {
    /**
     * 存储元素
     */
    private E value;

    /**
     * 下一个节点
     */
    private LinkedListQueue2<E> next;

    /**
     * 头节点
     * 头节点就是哨兵节点，尾节点就是存储最后一个元素的节点
     */
    private LinkedListQueue2<E> head;

    /**
     * 尾节点
     */
    private LinkedListQueue2<E> tail;

    public LinkedListQueue2() {
        init();
    }

    private LinkedListQueue2(E value) {
        this.value = value;
    }

    private void init() {
        head = new LinkedListQueue2<>();
        tail = head;
    }

    @Override
    public boolean offer(E e) {
        LinkedListQueue2<E> node = new LinkedListQueue2<>(e);
        tail.next = node;
        tail = node;
        tail.next = head;
        return true;
    }

    @Override
    public E poll() {
        if (head.next == head) {
            return null;
        }
        LinkedListQueue2<E> next = head.next;
        if (next.next == head) {
            head.next = head;
            tail = head;
        } else {
            head.next = next.next;
        }
        return next.value;
    }

    @Override
    public E peek() {
        if (head.next == head) {
            return null;
        }
        return head.next.value;
    }

    @Override
    public boolean isEmpty() {
        return (head == tail);
    }

    @Override
    public Iterator<E> iterator() {
        return new Itr();
    }

    @Override
    public void clear() {
        // ignore
    }

    @Override
    public int size() {
        return 0;
    }

    @Override
    public boolean isFull() {
        return false;
    }

    /**
     * 迭代器对象
     */
    private class Itr implements Iterator<E> {
        private LinkedListQueue2<E> temp = head.next;

        @Override
        public boolean hasNext() {
            return (temp != null && temp != head);
        }

        @Override
        public E next() {
            LinkedListQueue2<E> t2 = temp;
            temp = temp.next;
            return t2.value;
        }
    }
}
